package cn.tsoft.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.tsoft.demo.Student;
import cn.tsoft.service.StudentService;
import cn.tsoft.service.impl.StudentServiceImpl;

public class HttpAndroidServlet extends HttpServlet {
	
	private StudentService service = new StudentServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<Student> students =new ArrayList<Student>();
		try {
			students = service.getStudentList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if("json".equals(request.getParameter("form"))){
			StringBuilder json = new StringBuilder();
			json.append('[');
			for(Student student : students){ // {id:76,name:"xxxx",age:80}
				json.append('{');
				json.append("id:").append(student.getId()).append(',');
				json.append("name:\"").append(student.getName()).append("\",");
				json.append("age:").append(student.getAge());
				json.append('}').append(',');
			}
			json.deleteCharAt(json.length()-1);
			json.append(']');
			request.setAttribute("json", json.toString());
		}else{			
			request.setAttribute("videos", students);
		}
	}

}
